package SGUI

import (
	. "SGEngine2"
	"dom4g"
	//	"fmt"
)

func GenStackPanelByXML(elem *dom4g.Element, node *Node, tw *TopWidget, p IWidget) IWidget {
	newStackPanel := &StackPanel{}
	newStackPanel.Node = node
	newStackPanel.Top = tw
	parseNodeAttrs(elem, newStackPanel, p)
	if v, ok := elem.AttrValue("Orientation"); ok {
		if v == "Horizontal" {
			newStackPanel.Orientation = Horizontal
		} else if v == "Vertical" {
			newStackPanel.Orientation = Vertical
		}
	}
	return newStackPanel
}

type StackPanel struct {
	Orientation int
	WidgetInfo
}

func (this *StackPanel) GetWidgetInfo() *WidgetInfo {
	return &this.WidgetInfo
}

func (this *StackPanel) OnLoad() {
	this.Node.Bounds = new(Bounds)
	this.Node.Bounds.Center = Vec3Zero
	this.UpdateLayout()
}

func (this *StackPanel) UpdateLayout() {
	childArr := this.Node.GetChild()

	var addX, addY float32
	var sizex, sizey float32
	if childArr != nil {
		for i := 0; i < childArr.Count(); i++ {
			n := childArr.Get(i).(*Node)
			w := n.IfGet(IfGetIWidget)
			if w != nil {
				x, y := w.(IWidget).GetLayoutSize()
				sizey = y
				sizex = x
				Margin := w.(IWidget).GetWidgetInfo().Margin
				n.Position.Set(n.Position.X+float64(addX+Margin.Left), n.Position.Y+float64(addY+Margin.Top), 0)
				if this.Orientation == Horizontal {
					addX += x
				} else if this.Orientation == Vertical {
					addY -= y
				}
			}
		}
	}
	if this.Orientation == Horizontal {
		this.Node.Bounds.Max = Vec3{float64(addX), 0, 0}
		this.Node.Bounds.Min = Vec3{0, -float64(sizey), 0}
	} else if this.Orientation == Vertical {
		this.Node.Bounds.Max = Vec3{float64(sizex), 0, 0}
		this.Node.Bounds.Min = Vec3{0, float64(addY), 0}
	}

	//	fmt.Println(this.Node.Bounds)
}
